package com.frxuexi.park2303.notice

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingData
import androidx.paging.filter
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.NoticeBeanItem
import com.frxuexi.base.http.Const
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.ArouterManager
import com.frxuexi.park2303.R
import com.frxuexi.park2303.databinding.ActivityNoticeBinding
import com.frxuexi.park2303.news.NewsIntent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/app/NoticeActivity")
@AndroidEntryPoint
class NoticeActivity : BaseActivity<ActivityNoticeBinding, NoticeIntent, NoticeViewModel>() {
    val noticeAdapter by lazy { NoticeAdapter2() }
    override fun getVM(): NoticeViewModel {
        return viewModels<NoticeViewModel>().value
    }

    override fun getBind(): ActivityNoticeBinding {
        return ActivityNoticeBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        val list = it.data as Collection<NoticeBeanItem>
                        noticeAdapter.apply {
                            addData(list.filter { it.title.isNotEmpty() && it.content.isNotEmpty() }.sortedByDescending { it.id })
                            notifyDataSetChanged()
                        }
                    }

                    else -> {}
                }
            }
        }

    }

    override fun initView() {
        binding.noticeHead.apply {
            headBack.setOnClickListener {
                finish()
            }
            headTitle.setText("公告管理")
            headAdd.setOnClickListener {
                ArouterManager.navigation(this@NoticeActivity,"/app/NoticeAddActivity")
            }
        }
        binding.noticeRv.apply {
            adapter = noticeAdapter
            layoutManager = LinearLayoutManager(this@NoticeActivity)
        }

        noticeAdapter.setOnItemClickListener { adapter, view, position ->
            ArouterManager.navigation(this,"/app/NoticeDetailActivity","nid",noticeAdapter.data.get(position).id.toString())
        }



    }

    override fun onResume() {
        super.onResume()
        vm.sendIntent(NoticeIntent.getNoticeByUid(SPUtils.getInstance().getInt(Const.UID)))
    }

}